package edu.ecust.design.web.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import edu.ecust.design.annotation.DataModifyAuth;
import edu.ecust.design.domain.Suppliers;
import edu.ecust.design.domain.dto.UploadFile;
import edu.ecust.design.service.ISuppliersServive;
import edu.ecust.design.web.model.Limit;
import edu.ecust.design.web.model.Page;

/**
 * 经销商查询控制器
 * 
 * @author xiefei
 * 
 */
@Controller
@RequestMapping(value = "/supp")
public class SuppliersController extends BaseController {
	private static final Logger logger = Logger
			.getLogger(SuppliersController.class);
	@Autowired
	private ISuppliersServive suppliersServive;

	@Override
	public String init() {
		return "SuppliersManage";
	}

	/**
	 * 简单的全文搜索
	 * 
	 * @param search
	 * @param start
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public String querySuppliers(HttpServletResponse response, String search,
			Integer start, Integer limit) {
		Limit lit = initLimit(start, limit);
		Page<Suppliers> page = suppliersServive.searchFullText(search, lit);
		response.setContentType("text/html;charset=UTF-8");
		return write(page);
	}

	/**
	 * 更新数据
	 * 
	 * @param supp
	 * @return
	 */
	@DataModifyAuth(op = "经销商数据管理>更新经销商数据")
	@RequestMapping(value = "/updatesupp")
	@ResponseBody
	public String updateSuppliers(HttpServletRequest request, Suppliers supp) {
		Map<String, Boolean> result = new HashMap<String, Boolean>();
		result.put("success", false);
		if (supp != null) {
			Long suppId = supp.getId();
			try {
				if (suppId != null) {
					suppliersServive.update(supp);
				} else {
					suppliersServive.save(supp);
				}
				result.put("success", true);
			} catch (Exception e) {
				logger.error("updateSuppliers fail", e);
			}
		}
		String json = write(result);
		return json;
	}

	/**
	 * 删除多条数据
	 * 
	 * @param ids
	 * @return
	 */
	@DataModifyAuth(op = "经销商数据管理>删除经销商数据")
	@RequestMapping(value = "/deletesupp")
	@ResponseBody
	public String deleteSuppliers(HttpServletRequest request, Long... ids) {
		Assert.notNull(ids, " id is null");
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		map.put("success", false);
		try {
			for (Long id : ids) {
				suppliersServive.delete(id);
			}
			map.put("success", true);
		} catch (Exception e) {
			logger.error(" delete fail ", e);
		}
		return write(map);
	}

	/**
	 * 上传数据
	 * 
	 * @param form
	 * @return
	 */
	@DataModifyAuth(op = "经销商数据管理>通过excel导入经销商数据")
	@RequestMapping(value = "/uploadsupp")
	@ResponseBody
	public String importSuppliers(HttpServletRequest request, UploadFile form) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		map.put("success", false);
		if (form != null) {
			CommonsMultipartFile file = form.getFile();
			List<Suppliers> supps = getImportData(file);
			for (Suppliers supp : supps) {
				suppliersServive.save(supp);
			}
			map.put("success", true);
		}
		return write(map);
	}

	/**
	 * 导入文件并转换为可以保存的数据
	 * 
	 * @param file
	 * @return
	 */
	private List<Suppliers> getImportData(CommonsMultipartFile file) {
		List<Suppliers> list = new ArrayList<Suppliers>();
		if (file != null && !file.isEmpty()) {
			try {
				XSSFWorkbook book = new XSSFWorkbook(file.getInputStream());
				// sheet 总数
				int sheetNumber = book.getNumberOfSheets();
				DecimalFormat df = new DecimalFormat("0");
				for (int i = 0; i < sheetNumber; i++) {
					XSSFSheet sheet = book.getSheetAt(i);
					int sheetRows = sheet.getPhysicalNumberOfRows();
					for (int r = 1; r <= sheetRows; r++) {
						XSSFRow row = sheet.getRow(r);
						if (row != null) {
							XSSFCell suppTypeCell = row.getCell(0);
							XSSFCell supNameCell = row.getCell(1);
							XSSFCell contactCell = row.getCell(2);
							XSSFCell postCell = row.getCell(3);
							XSSFCell tel1Cell = row.getCell(4);
							XSSFCell tel2Cell = row.getCell(5);
							XSSFCell faxCell = row.getCell(6);
							XSSFCell emailCell = row.getCell(7);
							XSSFCell itemCell = row.getCell(8);
							XSSFCell remarkCell = row.getCell(9);
							XSSFCell cooperateCell = row.getCell(10);
							XSSFCell levelCell = row.getCell(11);
							if (supNameCell != null && contactCell != null) {
								String suppType = null;
								if (suppTypeCell != null) {
									suppType = suppTypeCell
											.getRichStringCellValue()
											.getString();
								}
								String supName = supNameCell
										.getRichStringCellValue().getString();
								String contact = contactCell
										.getRichStringCellValue().getString();
								String post = null;
								if (postCell != null) {
									post = postCell.getRichStringCellValue()
											.getString();
								}
								String tel1 = null;
								String tel2 = null;
								if (tel1Cell != null) {
									if (tel1Cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
										tel1 = df.format(tel1Cell
												.getNumericCellValue());
									} else {
										tel1 = tel1Cell
												.getRichStringCellValue()
												.getString();
									}
								}
								if (tel2Cell != null) {
									if (tel2Cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
										tel2 = df.format(tel2Cell
												.getNumericCellValue());
									} else {
										tel2 = tel2Cell
												.getRichStringCellValue()
												.getString();
									}
								}
								String fax = null;
								if (faxCell != null) {
									if (faxCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
										fax = df.format(faxCell
												.getNumericCellValue());
									} else {
										fax = faxCell.getRichStringCellValue()
												.getString();
									}
								}
								String email = null;
								String item = null;
								String remark = null;
								String cooperate = null;
								String level = null;
								if (emailCell != null) {
									email = emailCell.getRichStringCellValue()
											.getString();
								}
								if (itemCell != null) {
									item = itemCell.getRichStringCellValue()
											.getString();
								}
								if (remarkCell != null) {
									remark = remarkCell
											.getRichStringCellValue()
											.getString();
								}
								if (cooperateCell != null) {
									cooperate = cooperateCell
											.getRichStringCellValue()
											.getString();
								}
								if (levelCell != null) {
									level = levelCell.getRichStringCellValue()
											.getString();
								}
								Suppliers supp = new Suppliers();
								supp.setContact(contact);
								supp.setCooperate(cooperate);
								supp.setContact(email);
								supp.setFax(fax);
								supp.setItem(item);
								supp.setLevel(level);
								supp.setPost(post);
								supp.setRemark(remark);
								supp.setSupName(supName);
								supp.setSupType(suppType);
								supp.setTel1(tel1);
								supp.setTel2(tel2);
								list.add(supp);
							}
						}
					}
				}
			} catch (IOException e) {
				logger.error(" import supp fail ", e);
			}
		}
		return list;
	}
}
